// 添加重新连接摄像头的功能
document.getElementById('reconnect').addEventListener('click', function() {
    const videoImg = document.getElementById('videoStream');
    // 添加随机参数以避免缓存
    videoImg.src = '/video_feed?t=' + new Date().getTime();
});

// 每秒更新一次手柄数据
setInterval(function() {
    fetch('/joystick/latest')
        .then(response => response.json())
        .then(data => {
            if (data) {
                const joystickDiv = document.getElementById('joystick-data');
                const timestamp = new Date(data.timestamp * 1000).toLocaleString();
                joystickDiv.innerHTML = `
                    <div class="joystick-info">
                        <div class="joystick-side">
                            <h3>左摇杆</h3>
                            <p>X: <span class="value">${data.left_x}</span></p>
                            <p>Y: <span class="value">${data.left_y}</span></p>
                        </div>
                        <div class="joystick-side">
                            <h3>右摇杆</h3>
                            <p>X: <span class="value">${data.right_x}</span></p>
                            <p>Y: <span class="value">${data.right_y}</span></p>
                        </div>
                    </div>
                    <p>时间: ${timestamp}</p>
                `;
            }
        })
        .catch(error => console.error('获取手柄数据失败:', error));
        
    // 获取控制状态
    fetch('/robot/status')
        .then(response => response.json())
        .then(data => {
            const statusIndicator = document.getElementById('status-indicator');
            if (data.running) {
                statusIndicator.textContent = "状态: 运行中";
                statusIndicator.className = "status-running";
            } else {
                statusIndicator.textContent = "状态: 已停止";
                statusIndicator.className = "status-stopped";
            }
        })
        .catch(error => console.error('获取状态失败:', error));
}, 1000);

// 启动控制按钮
document.getElementById('start-control').addEventListener('click', function() {
    fetch('/robot/start', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        })
        .catch(error => console.error('启动控制失败:', error));
});

// 停止控制按钮
document.getElementById('stop-control').addEventListener('click', function() {
    fetch('/robot/stop', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        })
        .catch(error => console.error('停止控制失败:', error));
});
